<?php

namespace Beerus\Modules\Designer\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Doraemon\model\BlackList;
use Doraemon\model\Member;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;
use Doraemon\service\User;

/**
 * 黑名单管理
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */

class BlacklistController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    /**
     * 黑名单列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content)
    {
        $request_data = $request->all();

        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = [];
        if (!empty($request_data['uid'])) {
            $condition['uid'] = $request_data['uid'];
        }

        if (!empty($request_data['nick'])) {
            $uid = User::getUidByNick($request_data['nick']);
            $condition['uid'] = $uid;
        }

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = BlackList::select('*', $condition);

        $total = 0;
        if (!empty($lists)) {
            unset($condition['ORDER']);
            unset($condition['LIMIT']);
            $total = BlackList::count($condition);
            $user_ids = array_column($lists, 'uid');
            $member_info = Member::getUsers($user_ids);

            foreach ($lists as &$item) {
                $item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
            }
            unset($item);
        }

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', '用户UID')->placeholder('请输入uid');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
                    });
                    $filter->expand();
                });

                $grid->column("uid", '用户UID');
                $grid->column('nick', '用户昵称');

                $grid->column("type", '类别')->display(function () {
                    return BlackList::TYPE[$this->type];
                });

                $grid->column("remark", '备注');

                $grid->column("add_time", '创建时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->add_time);
                });

                $grid->column("edit_time", '修改时间')->display(function () {
                    if (empty($this->edit_time)) {
                        return '';
                    }
                    return date("Y-m-d H:i:s", $this->edit_time);
                });

                $grid->column("data_status", '数据状态')->display(function () {
                    return BlackList::STATUS[$this->data_status];
                });

                $grid->column("admin_id", '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                });
            }
        );

        $tab = new Tab();
        $tab->add('黑名单列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('黑名单列表')
            ->description(' ')
            ->breadcrumb(['text' => '黑名单列表']);
    }

    /**
     * 新增、修改黑名单
     * @param Request $request
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function edit(Request $request, Content $content, $id = 0)
    {
        $request = $request->all();

        if ($id == 0) {
            $is_create = true;
            $header = '添加黑名单';
        } else {
            $is_create = false;
            $header = '修改黑名单';
        }

        $tab = new Tab();
        $tab->add('黑名单信息', self::editAction($request, $id, $is_create));
        return $content->header($header)
            ->breadcrumb([
                'text' => '黑名单列表',
                'url' => route('blacklist')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = BlackList::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
        }

        $form->text('uid', '用户UID')->setWidth(4, 2)->required('不能为空');
        $form->select('type', '黑名单类别')->setWidth(4, 2)->options(BlackList::TYPE);
        $form->textarea('remark', '备注')->setWidth(4, 2);
        $form->select('data_status', '数据状态')->default(BlackList::STATUS_NORMAL)
            ->setWidth(4, 2)->options(BlackList::STATUS);

        $form->action('/admin/Designer/blacklist/save');

        return $form->render();
    }

    /**
     * 保存黑名单数据
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function editSubmit(Request $request)
    {
        $request = $request->all();

        $data = [
            'uid' => $request['uid'],
            'type' => $request['type'],
            'remark' => $request['remark'],
            'data_status' => $request['data_status'],
            'admin_id' => Admin::user()->id
        ];

        $now = time();
        if (isset($request['id'])) {
            $data['edit_time'] = $now;
            $id = $request['id'];

            $rs = BlackList::updateBlacklist($id, $data);
        } else {
            $where = [
                'uid' => $request['uid'],
                'type' => $request['type'],
            ];
            $same = BlackList::getByCondition($where);

            if (!empty($same)) {
                $error = new MessageBag([
                    'title' => '该用户已存在'
                ]);

                return back()->with(compact('error'));
            }

            $data['add_time'] = $now;

            $rs = BlackList::createBlacklist($data);
        }

        if ($rs) {
            if (isset($request['id'])) {
                $title = '修改成功';
            } else {
                $title = '添加成功';
            }

            $success = new MessageBag([
                'title' => $title
            ]);

            return redirect('/admin/Designer/blacklist')->with(compact('success'));
        } else {
            if (isset($request['id'])) {
                $title = '修改失败';
            } else {
                $title = '添加失败';
            }

            $error = new MessageBag([
                'title' => $title
            ]);

            return back()->with(compact('error'));
        }
    }
}
